package com.touchportfolio.loadQueue.loaders
{
	import com.touchportfolio.events.ErrorEvent;
	import com.touchportfolio.events.PayloadEvent;
	import com.touchportfolio.loadQueue.IQueueLoader;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	/**
	 * The XMLLoader class loads an XML file<br>
	 * The result can be found in 'dataXML'<br>
	 * <br>
	 * This class dispatches an ErrorEvent.ERROR with all the different errors that occured
	 **/
	
	public class XMLLoader extends URLLoader implements IQueueLoader
	{		
		private var _path:String;
		private var _data:XML;
		
		/**
		 * Contains, once loaded, all the XML data
		 * @return all the XML data in XML format
		 **/
		
		public function get dataXML():XML
		{
			return _data;
		}
		
		/**
		 * This is the constructor of the XMLLoader class
		 * @param path is the path to the XML file
		 **/
		
		public function XMLLoader(path:String)
		{
			_path = path;
		}
		
		/**
		 * By executing this function you start the actual loading process
		 **/
		
		public function run():void
		{
			addEventListener(Event.COMPLETE, onComplete);
			addEventListener(IOErrorEvent.IO_ERROR, IOErrorHandler);
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, SecurityErrorHandler);
			load(new URLRequest(_path));
		}
		
		private function onComplete(e:Event):void
		{
			try
			{
				_data = new XML(e.target.data);
				dispatchEvent(new PayloadEvent(_data, PayloadEvent.PAYLOAD));	
			}
			
			catch(e:TypeError)
			{
				dispatchEvent(new ErrorEvent(["Could not parse text into XML - "+ e.message], ErrorEvent.ERROR));
			}
		}
		
		private function IOErrorHandler(e:IOErrorEvent):void
		{
			dispatchEvent(new ErrorEvent(["IO error occurred while loading the XML \""+_path+"\", this could be because it doesn\'t exist"], ErrorEvent.ERROR));
		}
		
		private function SecurityErrorHandler(e:IOErrorEvent):void
		{
			dispatchEvent(new ErrorEvent(["Security error occurred while loading the XML \""+_path+"\""], ErrorEvent.ERROR));
		}
		
	}
}